"""
This module contains the logic of the drawing and updating of a background starfield
"""
import pygame
from pygame.locals import *
from random import *

class Starfield:
    """Container Group-like that will hold the stars floating"""
    P_SIZE = 5 # max size of a star
    def __init__(self, dimensions):
        """dimensions of the screen"""
        self.rect = dimensions
        self.stars = [] # each element is (x, y, movement factor)
        for i in range(50): 
            self.stars += [[random() * dimensions.w,\
                           random() * dimensions.h, random(), self._newcolor()]]

    def update(self, direction, zoom):
        """updates the position of each star and generate new ones when they
        escape the screen"""
        for i in self.stars:
            factor = i[2]
            i[0] += -direction[0] * factor * zoom
            i[1] += -direction[1] * factor * zoom
            if not self.rect.collidepoint(i[0], i[1]):
                if i[0] < 0:
                   i[0] = self.rect.w
                   i[1] = self.rect.h * random()
                if i[0] > self.rect.w:
                   i[0] = 0
                   i[1] = self.rect.h * random()
                if i[1] < 0:
                   i[1] = self.rect.h
                   i[0] = self.rect.w * random()
                if i[1] > self.rect.h:
                   i[1] = 0
                   i[0] = self.rect.w * random()
                i[2] = random()
                i[3] = self._newcolor()

    def draw(self, surface):
        """draw every star to the given surface"""
        for i in self.stars:
            pygame.draw.rect(surface, i[3], (i[0], i[1], Starfield.P_SIZE * i[2],\
                                             Starfield.P_SIZE*(1-i[2])))

    def clear(self, surface):
        """Cleans every star to the given surface (UNUSED)"""
        for i in self.stars:
            pygame.draw.rect(surface, (0, 0, 0), (i[0], i[1], Starfield.P_SIZE * i[2],\
                                                  Starfield.P_SIZE*(1-i[2]))) # clear the point
            
    def _newcolor(self):
        """Generates new random color"""
        if random() > 0.2:
            shade = randint(127, 255)
            return (shade, shade, shade)
        else:
            return (randint(127, 255),\
                    randint(127, 255),\
                    randint(127, 255),\
                    randint(127, 255))